use crate::{AppState, error::AppError};
use chat_core::Workspace;


impl AppState {
    pub async fn create_workspace(&self,name: &str,user_id: u64) -> Result<Workspace,AppError>{
        let ws = sqlx::query_as(
            "INSERT INTO workspaces (name,owner_id) VALUES ($1,$2) RETURNING id,name,owner_id,created_at"
        ).bind(name)
        .bind(user_id as i64)
        .fetch_one(&self.pool)
        .await?;
        Ok(ws)
    }

    pub async fn find_workspace_by_name(&self,name: &str) ->Result<Option<Workspace>,AppError>{
        let ws = sqlx::query_as(
            "SELECT id,name,owner_id,created_at FROM workspaces WHERE name = $1"
        ).bind(name)
        .fetch_optional(&self.pool)
        .await?;
        Ok(ws)
    }

    pub async fn find_workspace_by_id(&self,id: i64) ->Result<Option<Workspace>,AppError>{
        let ws = sqlx::query_as(
            "SELECT id,name,owner_id,created_at FROM workspaces WHERE id = $1"
        ).bind(id)
        .fetch_optional(&self.pool)
        .await?;
        Ok(ws)
    }

    pub async fn update_workspace_owner(
        &self,
        id: u64,
        owner_id: u64,
    ) -> Result<Workspace,AppError> {
        let ws = sqlx::query_as(
            "UPDATE workspace SET owner_id = $1
            WHERE id = $2 and (SELECT ws_id FROM users WHERE id = $1) = $2
            RETUENING id,name,owner_id,created_at"
        )
        .bind(owner_id as i64)
        .bind(id as i64)
        .fetch_one(&self.pool)
        .await?;
        Ok(ws)
    }
}